//
//  FaceViewModel.swift
//  NewWeiBo
//
//  Created by 吴天益 on 2017/8/3.
//  Copyright © 2017年 ttt. All rights reserved.
//

import UIKit
import YYModel

class FaceViewModel: NSObject {
    
    static let shareModel: FaceViewModel = FaceViewModel()
    
    override init() {
        super.init()
        
        
        //加载plist文件
        
    }
    
    //懒加载控件
    private lazy var normalFaceArray: [FaceModel] = {
        return self.loadBundlePlist(folderName: "default", fileName: "info.plist")
    }()
    private lazy var emojiFaceArray: [FaceModel] = {
        return self.loadBundlePlist(folderName: "emoji", fileName: "info.plist")
    }()
    private lazy var lxhFaceArray: [FaceModel] = {
        return self.loadBundlePlist(folderName: "lxh", fileName: "info.plist")
    }()
    //最近表情
    private lazy var recentFaceArray: [FaceModel] = [FaceModel]()
    
    
    //总的数组
    lazy var allArray: [[[FaceModel]]] = [
    
        [self.recentFaceArray],
        self.rowForArray(arr: self.normalFaceArray),
        self.rowForArray(arr: self.emojiFaceArray),
        self.rowForArray(arr: self.lxhFaceArray)
    ]
    
    //bundle
    var bundle: Bundle?
    
    
    //MARK: - 把没中表情数组按页数分行排
    func rowForArray(arr: [FaceModel]) -> [[FaceModel]]{
        
        //一页显示20个,每一页作为一item,每一页作为一个数组
        var num = 20
        
        let pageCount = (arr.count - 1)/num + 1
        
        var arrTwo = [[FaceModel]]()
        
        //截取元素
        for pageIndex in 0 ..< pageCount{
            
            let startIndex = pageIndex * num
            
            //最后不足20个的时候,就要截剩下的
            if pageIndex == pageCount - 1{
                num = arr.count - pageIndex * num
            }
            
            let subArray = (arr as NSArray).subarray(with: NSMakeRange(startIndex, num)) as! [FaceModel]
            
            arrTwo.append(subArray)
        }
        
        return arrTwo
  
    }
    
    //MARK: - 加载bundle里的plist封装
    func loadBundlePlist(folderName: String,fileName: String) -> [FaceModel] {
        
        //获取bundle里有contents和resourse情况下的plist文件
        let path = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil)
        
        let bundle = Bundle(path: path!)!
        
        //为属性赋值
        self.bundle = bundle
        
        //拼接小路径
        let samllPath = folderName + "/" + fileName
        
        let truePath = bundle.path(forResource: samllPath, ofType: nil)
        
        print("truePath" + truePath!)
        
        let arr = NSArray(contentsOfFile: truePath!)!
        
        //字典转模型
        let newArr = NSArray.yy_modelArray(with: FaceModel.self, json: arr) as! [FaceModel]
        
        
        //获取图片路径
        for model in newArr{
            if model.type == "0"{
                let imagePath = folderName + "/" + model.png!
                
                model.path = imagePath
            }
        }
        
        
        return newArr   
        
    }
    

}
